﻿

using IotClientService.Operations.bcr;
using IotContract.Dtos.Clients.Equips;
using IotContract.Dtos.Servers;
using IotContract.Events;
using IotContract.Interfaces;
using IotContract.Interfaces.Http;
using IotContract.Models.Clients;
using Newtonsoft.Json;
using SyncSocketModuleCore.SyncSocketModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IotClientService.Operations.Api;
public class ApiOperation : IEquipOperation<ApiEquipDto>
{
    private IClientWebService _clientWebService;
    private Task _operationTask;
    private CancellationTokenSource? _cancellationTokenSource;
    public ApiOperation(IClientWebService clientWebService)
    {
        _clientWebService = clientWebService;       
    }
    private ApiEquipDto _equipInfo;
   
    private bool _status = false;
    private bool _curConnection;
    public event EventHandler<ConnectStatusEventArgs> OnConnectStatusChanged;
    

    public void Dispose()
    {
        return;
    }

    public bool GetConnection()
    {
        return _curConnection;
    }

    public ApiEquipDto GetEquipInfo()
    {
        return _equipInfo;
    }

    public bool GetOperationStatus()
    {
        return _status;
    }

    public async Task<bool> Init(ApiEquipDto group, IEnumerable<EquipTagDto> tags = null)
    {
        
        _equipInfo = group;
        _curConnection = true;
        _status = true;
      
        _cancellationTokenSource = new CancellationTokenSource();
        return true;
    }

    public async Task<bool> OperationStart()
    {
        if (_operationTask != null && _curConnection)
        {
            await OperationStop();

        }

        if (_cancellationTokenSource == null)
        {
            return false;
        }



        _operationTask = Task.Factory.StartNew(() => ThreadScheduler(), _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

        _status = true;
        return true;
    }

    /// <summary>
    /// 任务
    /// </summary>
    /// <returns></returns>
    private async Task ThreadScheduler()
    {
        _clientWebService.EquipWarnEvent += _clientWebService_EquipWarnEvent;
        _clientWebService.ErrorEvent += _clientWebService_ErrorEvent;
        _clientWebService.ValueChangeEvent += _clientWebService_ValueChangeEvent;
        while (true)
        {
            if (_cancellationTokenSource?.IsCancellationRequested == true)
            {
                break;
            }
            try
            {
                // 推送报警

              
                await Task.Delay(_equipInfo.Pooling);
            }
            catch (Exception exception)
            {
                
                _curConnection = false;
                OnConnectStatusChanged?.Invoke(this, new ConnectStatusEventArgs
                {
                    Message = exception.Message,
                    Connect = _curConnection,
                    IsSuccess = false

                });
            }


        }
    }
    /// <summary>
    /// 值变化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <exception cref="NotImplementedException"></exception>
    private void _clientWebService_ValueChangeEvent(object? sender, string e)
    {
        _equipInfo.Value = e;
    }
    /// <summary>
    /// 错误
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <exception cref="NotImplementedException"></exception>
    private void _clientWebService_ErrorEvent(object? sender, string e)
    {
        _equipInfo.Remark = e;
    }
    /// <summary>
    /// 报警
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <exception cref="NotImplementedException"></exception>
    private void _clientWebService_EquipWarnEvent(object? sender, IotContract.Dtos.Clients.IotEquipWarnDto e)
    {
        // 报警
    }

    public async Task<bool> OperationStop()
    {
        _clientWebService.EquipWarnEvent -= _clientWebService_EquipWarnEvent;
        _clientWebService.ErrorEvent -= _clientWebService_ErrorEvent;
        _clientWebService.ValueChangeEvent -= _clientWebService_ValueChangeEvent;
        _cancellationTokenSource?.Cancel();

        _curConnection = false;

       

        _status = false;

        OnConnectStatusChanged.Invoke(this, new ConnectStatusEventArgs
        {
            Connect = false,
            IsSuccess = true,
        });

        return true;
    }

    public async Task<bool> WriteRequest(OperationWriteCommand writeInfo)
    {
        return true;
    }

   
}
